#!/usr/bin/env python3
"""
简化版OPC UA测试服务器
专门用于测试1#混流泵设备连接
"""

import asyncio
import logging
import random
import signal
import sys

try:
    from asyncua import Server, ua
    OPCUA_AVAILABLE = True
except ImportError:
    OPCUA_AVAILABLE = False

class SimpleOPCUAServer:
    def __init__(self):
        self.server = None
        self.running = False
        
    async def start(self):
        """启动简化OPC UA服务器"""
        if not OPCUA_AVAILABLE:
            print("❌ asyncua库未安装，请运行: pip install asyncua")
            return
            
        self.server = Server()
        await self.server.init()
        
        # 设置端点
        self.server.set_endpoint("opc.tcp://127.0.0.1:49320")
        self.server.set_server_name("Simple Industrial OPC Server")
        
        # 获取对象节点
        objects = self.server.get_objects_node()
        
        # 创建命名空间
        idx = await self.server.register_namespace("http://simple.industrial.opcua")
        
        # 创建简单的数值变量 - 直接在Objects下
        # 节点ID: ns=2;i=300 对应VD300
        self.vfd_freq = await objects.add_variable(idx, "VD300", 50.0)
        await self.vfd_freq.set_writable()
        
        print("✅ OPC UA服务器启动成功")
        print("📍 端点: opc.tcp://127.0.0.1:49320")
        print("🔧 测试节点: ns=2;i=300 (VD300)")
        print("⏹️  按 Ctrl+C 停止")
        
        # 启动服务器
        await self.server.start()
        self.running = True
        
        # 启动数据更新
        asyncio.create_task(self.update_data())
        
    async def update_data(self):
        """更新测试数据"""
        while self.running:
            try:
                # 模拟频率在45-55Hz之间波动
                freq = 50.0 + random.uniform(-5, 5)
                await self.vfd_freq.set_value(freq)
                await asyncio.sleep(1)
            except Exception as e:
                print(f"❌ 数据更新失败: {e}")
                await asyncio.sleep(5)
                
    async def stop(self):
        """停止服务器"""
        self.running = False
        if self.server:
            await self.server.stop()
            print("🛑 OPC UA服务器已停止")

async def main():
    """主函数"""
    logging.basicConfig(level=logging.WARNING)  # 减少日志输出
    
    server = SimpleOPCUAServer()
    
    # 信号处理
    def signal_handler(sig, frame):
        print("\n👋 正在停止服务器...")
        asyncio.create_task(server.stop())
    
    signal.signal(signal.SIGINT, signal_handler)
    
    try:
        await server.start()
        
        # 保持运行
        while server.running:
            await asyncio.sleep(1)
            
    except Exception as e:
        print(f"💥 服务器错误: {e}")
    finally:
        await server.stop()

if __name__ == "__main__":
    asyncio.run(main()) 